import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt


# 读取图像并进行边缘检测（这里省略了前面的步骤）
# ...
def auto_canny(image, sigma=0.33):
    # 计算图像的中位数
    v = np.median(image)

    # 使用中位数计算上下阈值
    lower = int(max(0, (1.0 - sigma) * v))
    upper = int(min(255, (1.0 + sigma) * v))

    # 应用Canny边缘检测
    edged = cv.Canny(image, lower, upper)

    return edged


# 读取图像并转换为灰度图
image = cv.imread('chair.bmp')
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

# 应用高斯模糊减少噪声
blurred = cv.GaussianBlur(gray, (9, 9), 0)

# 自动Canny边缘检测
edges = auto_canny(blurred)
lines = cv.HoughLinesP(edges, 1, np.pi / 180, threshold=32, minLineLength=42, maxLineGap=19)
# 创建霍夫空间的直方图
hough_space_rho = []
hough_space_theta = []

if lines is not None:
    for line in lines:
        x1, y1, x2, y2 = line[0]
        # 计算线段的rho和theta
        if x2 != x1:  # 避免除以零的情况
            slope = (y2 - y1) / (x2 - x1)
            theta = np.arctan(slope)
        else:
            theta = np.pi / 2  # 线段垂直时的角度为pi/2

        # 将角度转换为正数范围 [0, pi]
        if theta < 0:
            theta += np.pi

        rho = x1 * np.cos(theta) + y1 * np.sin(theta)
        hough_space_rho.append(rho)
        hough_space_theta.append(theta)

# 绘制霍夫空间
plt.figure(figsize=(10, 6))
plt.scatter(hough_space_theta, hough_space_rho, c='blue', marker='o')
plt.title('Hough Space (rho-theta)')
plt.xlabel('Theta (radians)')
plt.ylabel('Rho (pixels)')
plt.xlim([0, np.pi])
plt.grid(True)
plt.show()